<?php
namespace Components\Products\First;

class Filter extends \Phalcon\Filter implements \Phalcon\FilterInterface {
	private $data = [];
	private $errors = [];

	public function setData($data) {
		$this -> data = $data;
		return $this;
	}

	public function execute() {
		if(empty($this -> errors)) {
			return ['code'=>0,'data'=>$this->data];
		}

		return ['code'=>-1,'message'=>$this->errors[0]];
	}

	public function addProductsClassId() {
		$this -> data['products_class_id'] = $this -> sanitize($this -> data['products_class_id'], 'int');
		return $this;
	}

	public function addName() {
		$this -> data['name'] = $this -> sanitize($this -> data['name'], ['string','special_chars','trim']);
		return $this;
	}

	public function addImages() {
		if(isset($this -> data['images']) && !empty($this -> data['images']) && is_array($this -> data['images'])) {
			$t = [];
			foreach($this -> data['images'] as $v) {
				$t[] = $v;
			}
			$this -> data['images'] = json_encode($t);
		} else {
			$this -> data['images'] = json_encode([]);
		}
		return $this;
	}

	public function addPrice() {
		if(isset($this -> data['price_rmb']) && ($this -> data['price_rmb'] >= 0)) {
			$this -> data['price_rmb'] = $this -> sanitize($this -> data['price_rmb'], 'float');
		} else {
			$this -> data['price_rmb'] = 0;
		}

		if(isset($this -> data['price_retail']) && ($this -> data['price_retail'] >= 0)) {
			$this -> data['price_retail'] = $this -> sanitize($this -> data['price_retail'], 'float');
		} else {
			$this -> data['price_retail'] = 0;
		}

		if(isset($this -> data['price_shop']) && ($this -> data['price_shop'] >= 0)) {
			$this -> data['price_shop'] = $this -> sanitize($this -> data['price_shop'], 'float');
		} else {
			$this -> data['price_shop'] = 0;
		}

		if($this -> data['price_rmb'] <= 0 && $this -> data['price_retail'] <= 0 && $this -> data['price_shop'] <= 0) {
			$this -> errors[] = '必须有任意一个价格大于0';
		}

		return $this;
	}

	public function addStock() {
		if(isset($this -> data['stock']) && ($this -> data['stock'] >= 0)) {
			$this -> data['stock'] = $this -> sanitize($this -> data['stock'], 'int');
		} else {
			$this -> data['stock'] = 0;
		}

		if($this -> data['stock'] <= 0) {
			$this -> errors[] = '库存必须大于0';
		}

		return $this;
	}

	public function addDetails() {
		if(isset($this -> data['details']) && ($this -> data['details'] >= 0)) {
			$this -> data['details'] = htmlspecialchars_decode($this -> data['details']);
		}

		return $this;
	}

	public function addIsShelf() {
		$this -> data['is_shelf'] = $this -> sanitize($this -> data['is_shelf'], 'int');
		return $this;
	}

	public function addCreateTime() {
		$this -> data['create_time'] = time();
		return $this;
	}

	public function addLastUpdateTime() {
		$this -> data['last_update_time'] = time();
		return $this;
	}
}
